package com.lyn.system.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Model;
import com.lyn.common.base.BaseService;
import com.lyn.common.base.Result;
import com.lyn.domain.User;

public class UserService extends BaseService {
    public static final UserService me = new UserService();
    @Override
    public Model<?> getDao() {
        return User.dao;
    }

    /**
     * 插入一行记录
     * 测试通过
     * @param data
     * @return
     */
    public Result insert(String data) {
        logger.info("插入一个新用户");

        User user = JSONObject.parseObject(data, User.class);
        return baseInsert(user);
    }

    /**
     * 根据主键更新一条记录
     * 测试通过
     * @param data
     * @return
     */
    public Result updateById(String data) {
        //如果前端json未拼接nickName字段，则update语句中set并不会出现nickName
        //如果前端json拼接了"nickName": null，则update语句中会出现set nickName=null
        //如果在后端手工设置user.setNickName(null); 则update语句中会出现set nickName=null
        User user = JSONObject.parseObject(data, User.class);
        return baseUpdateById(user);
    }

    /**
     * 根据主键更新多条记录
     * 测试通过
     * @param dataArray
     * @return
     */
    public Result updatesById(String dataArray) {
        JSONArray ja = JSONArray.parseArray(dataArray);
        return baseUpdatesById(ja, User.class);
    }

    /**
     * 自定义条件更新若干条记录
     * @param data
     * @return
     */
    public Result customUpdate(String data) {
        User user = JSONObject.parseObject(data, User.class);
        Kv setParam = Kv.by("password", user.getPassword())
                .set("nick_name", user.getNickName());
        Kv whereParam = Kv.by("user_id", user.getUserId())
                .set("email", user.getEmail());
        //也可以传入驼峰命名的字段名，因为内部会做处理
//      Kv setParam = Kv.by("password", user.getPassword())
//              .set("nickName", user.getNickName());
//      Kv whereParam = Kv.by("userId=", user.getUserId())
//              .set("email=", user.getEmail());
        return baseCustomUpdate(setParam, whereParam);
    }

    //测试通过
    public Result getById(int id) {
        return baseGetById(id);
    }

    //测试通过
    public Result customSelect(String userId, String email) {
        String fields = "id, user_id, nick_name, password, email ";
        Kv whereParam = Kv.by("user_id=", userId).set("email=", email);
        //也可以传入驼峰命名的字段名，因为内部会做处理
//      String fields = "id, userId, nickName, password, email ";
//      Kv whereParam = Kv.by("userId=", userId).set("email=", email);
        return baseCustomSelect(fields, whereParam);
    }

    //测试通过
    public Result getByPage(int pageNumber, int pageSize, String email) {
        String selectSql = "select * ";
        Kv whereParam = Kv.by("id is not null", null).set("email like ", "%"+email+"%");
        return baseCustomGetByPage(pageNumber, pageSize, selectSql, whereParam);
    }
}
